from django import http
from django.shortcuts import render
from django.views import View

from meiduo1.libs.captcha.captcha import captcha
from django_redis import get_redis_connection

from meiduo1.libs.yuntongxun.sms import CCP
import random

from meiduo1.utils.response_code import RETCODE, RET

from .constants import REDIS_SMS_CODE, REDIS_IMAGE_CODE_EXPIRES, REDIS_SEND_FLAG_EXPICT


class ImageCodViwe(View):

    def get(self,request,image_code_id):
        #生成图片验证码
        text, image_data = captcha.generate_captcha()
        #保存图片验证码到redis
        redis_coon = get_redis_connection('code')

        redis_coon.setex('image_code_%s'%image_code_id,60,text)
        #返回响应
        return http.HttpResponse(image_data,content_type='image/png')

class SmsCodeView(View):

    def get(self,request,mobile):
        #获取参数
       image_code = request.GET.get('image_code')

       image_code_id = request.GET.get('image_code_id')

       if not all([image_code,image_code_id]):

            return http.JsonResponse({'errmsg':'参数不全','code':RET.PARAMERR})
       #校验图片验证码的正确性
       redis_conn = get_redis_connection('code')#取值

       redis_image_code = redis_conn.get('image_code_%s'%image_code_id)

       #验证验证码是否过期
       if not redis_image_code:

           return http.JsonResponse({'errmsg': '验证码失效', 'code':RETCODE.IMAGECODEERR})
       #没有过期就要删掉
       redis_conn.delete('image_code_%s'%image_code_id)
        #判断正确性
       if image_code.lower() != redis_image_code.decode().lower():

           return http.JsonResponse({'errmsg': '验证码错误', 'code':RETCODE.IMAGECODEERR})
       #判断是否频繁发送
       send_flag = redis_conn.get("send_flag_%s"%mobile)

       if send_flag:

           return http.JsonResponse({"errmsg":"发送频繁",'code': RET.SMSCODERR})

       sms_code = '%06d'%random.randint(0,999999)
       print(sms_code)
       #ccp = CCP()
       # ccp.send_template_sms(mobile, [sms_code, REDIS_SMS_CODE/60],1)
       pipeline = redis_conn.pipeline()
       pipeline.setex('sms_code_%s'%mobile,REDIS_IMAGE_CODE_EXPIRES,sms_code)

       pipeline.setex("send_flag_%s"%mobile,REDIS_SEND_FLAG_EXPICT,1)
       pipeline.execute()
       #返回响应
       return http.JsonResponse({'errmsg': '发送成功', 'code': RETCODE.OK})